<template>
	<div class="container">
		<!-- 展示区域 -->
		<div class="map-container" ref="mapContainer" >
			<!-- 动态路径绘制 -->
			<svg v-if="pathSegments.length" class="path-svg" :width="mapBaseSize.width" :height="mapBaseSize.height"
				:viewBox="`0 0 ${mapBaseSize.width} ${mapBaseSize.height}`">

				<path v-for="(segment, index) in validSegments" :key="'path-'+index" :d="genPathCommand(segment)"
					stroke="#2196F3" stroke-width="4" fill="none" :style="getLineStyle(index)">
					<animate v-if="shouldAnimate" attributeName="stroke-dashoffset" from="-100%" to="0" dur="2s"
						begin="0s" fill="freeze" />
				</path>
			</svg>
			<!-- 地图点位展示 -->
			<div v-for="point in points" class="map-point" :style="pointStyle(point)" @click="handlePointClick(point)"
				:class="{
			    [getPointClass(point.pointType)]: true,
			    'start-point': startPoint?.pointId === point.pointId,
			    'end-point': endPoint?.pointId === point.pointId
			  }">
				<div class="point-label">{{ point.pointName }}</div>
			</div>
		</div>
		<!-- 编辑区域 -->
		<div class="editor-panel">
			<div class="path-config">
				<h3>路径规划配置</h3>
				<div class="current-selection">
					<div>当前选中：{{ selectedPoint?.pointName || '无' }}</div>
					<div class="coordinate">
						({{ selectedPoint?.locationx }}, {{ selectedPoint?.locationy }})
					</div>
				</div>
				<div class="button-group">
					<button class="start-btn" @click="setStartPoint" :disabled="!selectedPoint">
						{{ startPoint ? '取消起点' : '设为起点' }}
					</button>
					<button class="end-btn" @click="setEndPoint" :disabled="!selectedPoint">
						{{ endPoint ? '取消终点' : '设为终点' }}
					</button>
				</div>

				<div v-if="startPoint || endPoint" class="selected-info">
					<div v-if="startPoint" class="start-info">
						🚩 起点: {{ startPoint.pointName }} (ID: {{ startPoint.pointId }})
					</div>
					<div v-if="endPoint" class="end-info">
						🏁 终点: {{ endPoint.pointName }} (ID: {{ endPoint.pointId }})
					</div>
				</div>

				<button class="plan-btn" @click="sendPoints" :disabled="!startPoint || !endPoint">
					开始路径规划
				</button>
			</div>
		</div>
	</div>
</template>

<script setup>
	const mapBaseSize = reactive({
		width: 1920,
		height: 1080
	});
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue';
	import {
		ElMessage
	} from 'element-plus';
	import {
		wcao,
		post,
		rgvpost
	} from "@/http";
	import axios from 'axios';
	import './css/kong0224.css';
	// 缩放相关状态
	const scale = ref(1);
	// 拖拽相关状态
	const isDragging = ref(false);
	const draggingPoint = ref(null);
	const dragStartPos = reactive({
		x: 0,
		y: 0
	});
	const mapContainer = ref(null);



	// 点位数据
	let maxPointId = 3;
	const points = ref([]);
	const loadPoints = async () => {
		try {
			let response = await axios.post('/points/getAll'); // 替换为实际的 API 地址
			console.log('加载点位个数:' + response.data.length);
			if (!Array.isArray(response.data)) {
				throw new Error(`无效的响应类型，预期数组，实际得到: ${typeof response.data}`);
			}
			// 数据转换
			let validPoints = response.data
				.map(p => ({
					pointId: Number(p.pointId),
					pointName: p.pointName || '未命名',
					pointType: p.pointType || 'DEFAULT',
					locationx: Number(p.locationX) || 0,
					locationy: Number(p.locationY) || 0,
					nodeId: p.nodeId
				}))
				.filter(p => Number.isInteger(p.pointId) && p.pointId > 0);

			// 更新状态
			points.value = validPoints;
			maxPointId = validPoints.length > 0 ?
				Math.max(...validPoints.map(p => p.pointId)) :
				0;

		} catch (error) {
			console.log('加载失败:', error);

			points.value = [{
				pointId: 1,
				pointName: '示例车-1',
				pointType: 'CAR', // 新增类型字段
				locationx: 50, // 原x
				locationy: 50, // 原y
				nodeId: 'rgv.rgv.sdf1' // 新增节点ID
			}, {
				pointId: 2,
				pointName: '示例转-1',
				pointType: 'TRANSFER', // 新增类型字段
				locationx: 50, // 原x
				locationy: 100, // 原y
				nodeId: 'rgv.rgv.sdf2' // 新增节点ID
			}, {
				pointId: 3,
				pointName: '示例库-1',
				pointType: 'WAREHOUSE', // 新增类型字段
				locationx: 50, // 原x
				locationy: 150, // 原y
				nodeId: 'rgv.rgv.sdf3' // 新增节点ID
			}];
			maxPointId = 0;
			ElMessage.error(`加载失败,仅展示默认的点位示例`);
		}
	};
	const svgStyle = computed(() => ({
		width: `${mapBaseSize.width}px`,
		height: `${mapBaseSize.height}px`,
		viewBox: `0 0 ${mapBaseSize.width} ${mapBaseSize.height}` // 添加svg坐标系
	}));
	// 轨道数据
	const tracks = ref([]);
	const selectedTrack = ref(null);

	// 轨道创建相关状态
	const trackStartPoint = ref(null); // 轨道起点
	const isCreatingTrack = ref(false); // 是否正在创建轨道
	// 轨道点击处理
	const handleTrackClick = (event) => {
		let trackId = event.target.getAttribute('data-track-id');
		if (trackId) {
			let track = tracks.value.find(t => t.id === Number(trackId));
			if (track) {
				selectedTrack.value = track;
				showMessage(`选中轨道：${track.name}`, 'info');
			}
		}
	};
	// 选中点位与编辑状态
	const selectedPoint = ref(null);
	const isEditing = ref(false);
	// 起点终点设置
	const startPoint = ref(null);
	const endPoint = ref(null);

	// 编辑区域拖拽相关状态
	const isPanelDragging = ref(false);
	const panelDragStartPos = reactive({
		x: 0,
		y: 0
	});
	const editorPanel = ref(null);

	// 工具函数：限制数值范围
	const clamp = (value, min, max) => Math.max(min, Math.min(max, value));

	// 限制点位坐标在地图容器范围内
	// 添加缩放比例计算
	const clampX = (value) => {
		if (mapContainer.value) {
			let maxX = (mapContainer.value.offsetWidth - 10) / scale.value;
			return Math.round(clamp(value, 0, maxX));
		}
		return Math.round(value);
	};
	const clampY = (value) => {
		if (mapContainer.value) {
			let maxY = (mapContainer.value.offsetHeight - 10) / scale.value;
			return Math.round(clamp(value, 0, maxY));
		}
		return Math.round(value);
	};
	// 点位样式计算
	// const pointStyle = (point) => ({
	// 	left: `${point.locationx * scale.value}px`,
	// 	top: `${point.locationy * scale.value}px`,
	// 	transform: `translate(-50%, -50%) scale(${1/scale.value})` // 保持视觉大小稳定
	// });
	const pointStyle = (point) => ({
		left: `${point.locationx}px`, // 移除缩放计算
		top: `${point.locationy}px`,
		transform: `translate(-50%, -50%)` // 移除缩放
	});

	// 根据点位名称获取样式类
	const getPointClass = (pointType) => {
		switch (pointType) {
			case 'CAR':
				return 'car-point';
			case 'WAREHOUSE':
				return 'warehouse-point';
			case 'TRANSFER':
				return 'transfer-point';
			default:
				return 'default-point';
		}
	}
	// 拖拽启动
	const startDrag = (point, event) => {
		if (isEditing.value) return;

		isDragging.value = true;
		draggingPoint.value = point;
		// 记录实际坐标属性
		dragStartPos.x = event.clientX - point.locationx * scale.value;
		dragStartPos.y = event.clientY - point.locationy * scale.value;

		// 立即选中该点位
		if (selectedPoint.value?.id !== point.pointId) {
			selectedPoint.value = point;
		}
	};

	// 拖拽处理
	const handleDrag = (event) => {
		if (!isDragging.value || !mapContainer.value) return;

		let containerRect = mapContainer.value.getBoundingClientRect();
		let rawX = event.clientX - containerRect.left - dragStartPos.x;
		let rawY = event.clientY - containerRect.top - dragStartPos.y;

		let newX = Math.round(rawX / 20) * 20;
		let newY = Math.round(rawY / 20) * 20;
		// 应用坐标限制
		draggingPoint.value.locationx = clampX(newX);
		draggingPoint.value.locationy = clampY(newY);
		// 强制触发数组更新（Vue3 需解构新对象）
		points.value = [...points.value];
	};

	// 停止拖拽
	const stopDrag = () => {
		console.log('无操作，鼠标划过了地图');
		if (draggingPoint.value && draggingPoint.value.pointId && selectedPoint.value.pointId) {
			let tuozhuaihou = {
				pointId: selectedPoint.value.pointId,
				pointName: selectedPoint.value.pointName,
				pointType: selectedPoint.value.pointType,
				locationX: selectedPoint.value.locationx,
				locationY: selectedPoint.value.locationy,
				nodeId: selectedPoint.value.nodeId
			};
			let response = axios.post('/points/update', tuozhuaihou);
			isDragging.value = false;
			draggingPoint.value = null;
		}

	};

	// 点位点击处理
	const handlePointClick = (point) => {
		selectedPoint.value = point;
		// 新增逻辑：如果已经设置过起点/终点，再次点击时显示对应信息
		if (startPoint.value?.pointId === point.pointId || endPoint.value?.pointId === point.pointId) {
			selectedPoint.value = point;
		}
	};

	// 设置起点/终点
	const setStartPoint = () => {
		if (!selectedPoint.value) return;

		if (startPoint.value?.pointId === selectedPoint.value.pointId) {
			startPoint.value = null;
			ElMessage.info('起点已取消');
		} else {
			startPoint.value = selectedPoint.value;
			ElMessage.success('起点设置成功');
		}
	};

	const setEndPoint = () => {
		if (!selectedPoint.value) return;

		if (endPoint.value?.pointId === selectedPoint.value.pointId) {
			endPoint.value = null;
			ElMessage.info('终点已取消');
		} else {
			endPoint.value = selectedPoint.value;
			ElMessage.success('终点设置成功');
		}
	};
	let pathSegments = ref([]); // 路径段数据
	let pathPoints = ref([]); // 完整路径点

	// 发送路径规划请求
	const sendPoints = async () => {
		if (!startPoint.value || !endPoint.value) {
			ElMessage.warning('请设置起点和终点');
			return;
		}

		try {
			const params = {
				start: {
					nodeId: startPoint.value.nodeId,
					x: startPoint.value.locationx,
					y: startPoint.value.locationy,
					pointType: startPoint.value.pointType
				},
				end: {
					nodeId: endPoint.value.nodeId,
					x: endPoint.value.locationx,
					y: endPoint.value.locationy,
					pointType: endPoint.value.pointType
				}
			};
			console.log('打印起终点');
			console.log(params);
			const response = await axios.post('/device/dispatch', params);
			console.log('打印获取到的路径数据');
			console.log(response);
			// 修改数据处理逻辑
			if (response.data.path?.length && response.data.segments?.length) {
				pathPoints.value = response.data.path.map(p => ({
					x: Number(p.x) || 0,
					y: Number(p.y) || 0,
					system: p.system || 'CUSTOM'
				}));

				pathSegments.value = response.data.segments.map(s => {
					if (typeof s === 'string') return s;
					// 如果有对象格式的segment，转换为字符串格式
					return `${s.from.x},${s.from.y} -> ${s.to.x},${s.to.y}`;
				});
			}
			// 在sendPoints函数添加调试信息
			console.log('在sendPoints函数添加调试信息生成路径段:', {
				requestParams: params,
				responseData: response.data,
				normalizedPath: pathPoints.value,
				normalizedSegments: pathSegments.value
			});
		} catch (error) {
			console.error('请求失败:', error);
			ElMessage.error('路径规划失败');
		}
	};
	// 计算属性确保有效路径段
	const validSegments = computed(() => {
		return pathSegments.value.filter(s => {
			if (typeof s !== 'string') return false;
			return s.includes('->') && s.split('->').every(p => p.includes(','));
		});
	});

	const shouldAnimate = computed(() => validSegments.value.length > 0);

	// 编辑操作
	const startEditing = () => {
		isEditing.value = true;
	};

	// 消息提示
	const showMessage = (text, type) => {
		ElMessage({
			message: text,
			type: type === 'error' ? 'error' : 'success',
		});
	};


	// 编辑区域拖拽启动
	const startPanelDrag = (event) => {
		isPanelDragging.value = true;
		panelDragStartPos.x = event.clientX - editorPanel.value.offsetLeft;
		panelDragStartPos.y = event.clientY - editorPanel.value.offsetTop;

		document.addEventListener('mousemove', handlePanelDrag);
		document.addEventListener('mouseup', stopPanelDrag);
	};

	// 编辑区域拖拽处理
	const handlePanelDrag = (event) => {
		if (!isPanelDragging.value) return;

		let left = event.clientX - panelDragStartPos.x;
		let top = event.clientY - panelDragStartPos.y;

		editorPanel.value.style.left = `${left}px`;
		editorPanel.value.style.top = `${top}px`;
	};

	// 停止编辑区域拖拽
	const stopPanelDrag = () => {
		isPanelDragging.value = false;
		document.removeEventListener('mousemove', handlePanelDrag);
		document.removeEventListener('mouseup', stopPanelDrag);
	};

	// 路径处理函数
	const genPathCommand = (segmentStr) => {
		try {
			// 假设后端返回的segment格式如："420,500 -> 640.5,320.8"
			const [startPart, endPart] = segmentStr.split('->').map(s => s.trim());
			const start = parseCoordinate(startPart);
			const end = parseCoordinate(endPart);
			return `M ${start.x} ${start.y} L ${end.x} ${end.y}`;
		} catch (e) {
			console.error('路径段格式错误:', segmentStr);
			return '';
		}
	}
	const parseCoordinate = (str) => {
		const [x, y] = str.split(',').map(Number);
		return {
			x: x || 0,
			y: y || 0
		};
	}
	const getPathLength = (segment) => {
		const start = pathPoints.value[segment.from];
		const end = pathPoints.value[segment.to];
		return Math.hypot(end.x - start.x, end.y - start.y);
	};

	const getAnimationDuration = (speed) => {
		const baseSpeed = 2; // 基础速度因子
		return `${baseSpeed / speed}s`; // 速度越快动画时间越短
	};

	const getSegmentColor = (speed) => {
		const speedLevels = [{
				threshold: 3,
				color: '#FF5722'
			}, // 高速-橙色
			{
				threshold: 2,
				color: '#4CAF50'
			}, // 中速-绿色
			{
				threshold: 1,
				color: '#2196F3'
			}, // 低速-蓝色
		];

		return speedLevels.find(l => speed >= l.threshold)?.color || '#9E9E9E';
	};

	// 修改动画获取方式
	const getLineStyle = (index) => {
		if (!validSegments.value[index]) return {};

		// 动态计算path长度（示例更精准的获取方式）
		const pathRef = ref(null);
		let totalLength = 0;
		onMounted(() => {
			if (pathRef.value)
				totalLength = pathRef.value.getTotalLength().toFixed(1)
		});

		return {
			strokeDasharray: totalLength * 2,
			strokeDashoffset: totalLength * 2,
			ref: pathRef // Vue3的自定义ref引用
		};
	}
	const calculateSegmentLength = (segmentStr) => {
		const path = segmentStr.split('->').map(p => {
			const [x, y] = p.trim().split(',').map(Number);
			return {
				x,
				y
			};
		});

		if (path.length < 2) return 0;

		let total = 0;
		for (let i = 1; i < path.length; i++) {
			total += Math.hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y);
		}
		return total;
	}
	// 触发路径动画
	const triggerPathAnimation = () => {
		pathSegments.value = [...pathSegments.value];
	};
	// 在控制台检查数据结构
	onMounted(() => {
		console.log('DOM 已挂载，mapContainer:', mapContainer.value);
		loadPoints();
	});
</script>

<style scoped>
	/* 地图展示区 */
	.map-container {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: #e8eaf6;
		overflow: hidden;
		transform-origin: 0 0;
		background-image: linear-gradient(to right, rgba(0, 0, 0, 0.1) 1px, transparent 1px),
			linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 1px, transparent 1px);
		 background-size: 20px 20px; /* 固定网格尺寸 */
	}
</style>